<template>
    <div>
        <br/>
        <br/>
        <el-form ref="route" :model="ltname" >
            <el-form-item label="商品名称" :label-width="formLabelWidth">
                <el-input placeholder="请输入内容" v-model="ltname.labelName" class="input-with-select" clearable>
                    <el-button slot="append" @click="listByRoute('labelName')" icon="el-icon-search"></el-button>
                </el-input>
            </el-form-item>
        </el-form>

<!--        <el-button type="warning" round @click="dialogFormVisible = true">新增商品</el-button>-->
        <el-button type="primary" round @click="dialogFormVisible = true" plain>新增商品</el-button>

        <el-dialog :title="title" :visible.sync="dialogFormVisible" @close="resetForm"> <!--取消后清空表格中数据-->
            <el-form :model="empInfo" :rules="rules" ref="empInfo">
                <!--<el-form-item label="商品编号" :label-width="formLabelWidth" prop="tid">
                    <el-input placeholder="请输入商品编号" v-model="empInfo.tid" :disabled="ttt" ></el-input>
                </el-form-item>-->
                <el-form-item label="商品名称" :label-width="formLabelWidth" prop="labelName">
                    <el-input placeholder="请输入商品名称" v-model="empInfo.labelName" ></el-input>
                </el-form-item>
                <el-form-item label="商品详情" :label-width="formLabelWidth" prop="shortDesc">
                    <!--多行文本框-->
                    <el-input type="textarea" :rows="5" placeholder="请输入商品详情" v-model="empInfo.shortDesc"></el-input>
                </el-form-item>
                <el-form-item label="商品价格" :label-width="formLabelWidth" prop="price">
                    <el-input placeholder="请输入商品价格" v-model.number="empInfo.price" ></el-input>
                </el-form-item>
                <el-form-item label="商品库存" :label-width="formLabelWidth" prop="store">
                    <el-input placeholder="请输入商品库存" v-model.number="empInfo.store"></el-input>
                </el-form-item>
                <el-form-item label="商品图片" :label-width="formLabelWidth" >
                    <img class="productPicWidth" :src="getUrl(defaultPic)" alt="">
                    <el-upload
                        class="upload-demo"
                        :action="insertUrl()"
                        :show-file-list="false"
                        :on-success="handleAvatarSuccess"
                        :before-upload="beforeAvatarUpload"
                    >
                        <el-button size="mini">更新图片</el-button>
<!--                        <i class="el-icon-upload"></i>-->
<!--                        <div class="el-upload__text">将文件拖到此处，或<em>点击上传图片</em></div>-->
<!--                        <div class="el-upload__tip" slot="tip">只能上传jpg/png文件，且不超过10M</div>-->
                    </el-upload>
                </el-form-item>
            </el-form>

            <div slot="footer" class="dialog-footer">
                <el-button @click="resetForm">取 消</el-button>
                <el-button type="primary" @click="sub('empInfo')">确 认</el-button>
            </div>
        </el-dialog>

        <hr/>

        <el-table :data="data"
                  tooltip-effect="dark"
                  style="width: 100%"
                  @selection-change="handleSelectionChange">
            <el-table-column prop="tid" label="商品编号"></el-table-column>

            <el-table-column prop="labelName" label="商品名称"></el-table-column>
            <el-table-column prop="picPath" label="商品图片">
                <template slot-scope="scope">
                    <img class="productPicWidth" :src="getUrl(scope.row.picPath)" alt="">
                </template>
            </el-table-column>
            <el-table-column prop="shortDesc" label="商品详情"></el-table-column>
            <el-table-column prop="price" label="商品价格"></el-table-column>
            <el-table-column prop="store" label="库存"></el-table-column>
            <el-table-column prop="createDate" label="创建时间" width="170px"></el-table-column>
            <el-table-column prop="updateDate" label="修改时间" width="170px"></el-table-column>

            <el-table-column prop="state" label="状态">
                <template slot-scope="scope">
                    <el-tag type="success" v-if="scope.row.state === 0" @click="updateState(scope.row)">商品正常</el-tag>
                    <el-tag type="danger" v-if="scope.row.state === 1" @click="updateState(scope.row)">商品未上架</el-tag>
                </template>

                <!--<template slot-scope="scope">
                    <el-tooltip :content="'商品状态: ' + value" placement="top">
                        <el-switch
                            v-model="scope.row.state"
                            active-color="#13ce66"
                            inactive-color="#ff4949"
                            active-value="100"
                            inactive-value="0"
                            change="updateState(scope.row)">
                        </el-switch>
                    </el-tooltip>
                </template>-->


            </el-table-column>

            <el-table-column>
                <template slot-scope="scope">
                    <i class="el-icon-edit" @click="update(scope.row)"></i>
                </template>
            </el-table-column>
        </el-table>
        <br/>
        <div class="page">
            <el-pagination
                background
                center
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page.sync="currentPage"
                :page-size="pageSize"
                :page-sizes="pageList"
                layout="total, sizes, prev, pager, next, jumper"
                :total="list.length">
                <!--           layout加上 sizes,    :page-sizes="[6, 7, 8, 9 ,10]"-->
            </el-pagination>
        </div>
    </div>
</template>

<script>
    export default {
        name: "Product",
        inject:['reload'],//注入reload方法
        data() {
            return {
                // value: '100',
                // 默认图片
                defaultPic: "1.jpg",
                // 当前页
                currentPage: 1,
                // 每页显示 5 条数据
                pageSize: 5,
                // 每页显示多少条数据的数组
                pageList: [5,10,15,20],
                list: [],
                empInfo: {

                },
                ttt: false,
                ltname:{
                    labelName:null
                },
                dialogFormVisible: false,
                formLabelWidth: '120px',
                title: "新增商品",
                rules: { //校验输入框输入规则
                    /*tid:[
                        { required: true, message: '请输入商品编号', trigger: 'blur' },
                        // { min: 5, max: 80, message: '长度在 5 到 80 个字符', trigger: 'blur' }
                    ],*/
                    labelName:[
                        { required: true, message: '请输入商品名称', trigger: 'blur' },
                        { min: 2, max: 30, message: '长度在 2 到 30 个字符', trigger: 'blur' }
                    ],
                    shortDesc:[
                        { required: true, message: '请输入商品详情', trigger: 'blur' },
                        { min: 2, max: 30, message: '长度在 2 到 30 个字符', trigger: 'blur' }
                    ],
                    price:[
                        { required: true, message: '请输入商品价格', trigger: 'blur'},
                        { type: 'number', message: '请输入数字', trigger: 'blur'}
                    ],
                    store:[
                        { required: true, message: '请输入商品库存', trigger: 'blur'},
                        { type: 'number', message: '必须为数字值', trigger: 'blur'}
                    ],
                }
            }
        },

        created() {
            this.$http.post("product/product/selectAll").then(data => {
                this.list = data.data;
            })
        },
        computed: {
            // 计算分页所显示的数据
            data() {
                if(this.list != null){
                    // 使用 splice 方法从第几个开始取出多少条数据
                    return this.list.slice((this.currentPage - 1) * this.pageSize, this.currentPage * this.pageSize);
                }

            }
        },
        methods:{
            // 修改当前页显示 多少数据
            handleSizeChange(val) {
                // console.log(`每页 ${val} 条`);
                this.pageSize = val;
            },
            // 修改当前是 第几页
            handleCurrentChange(val) {
                // console.log(`当前页: ${val}`);
                this.currentPage = val;
            },
            sub(formName) {
                // 对整个表单进行校验
                this.$refs[formName].validate((valid) =>{
                    if (valid){
                        this.empInfo.picPath = this.defaultPic;
                        console.log(this.empInfo)
                        this.$http.post("product/product/saveOrUpdate", this.empInfo).then(data => {
                            if (data) {
                                this.$message({
                                    type: 'success',
                                    message: '成功!'
                                });
                                this.reload()//直接调用刷新方法
                            } else {
                                this.$message({
                                    type: 'info',
                                    message: '失败!'
                                });
                                this.reload()//直接调用刷新方法
                            }
                        })
                    }else {
                        console.log('error submit!!')
                        return false;
                    }
                })
            },
            update(row) {
                this.title='修改商品信息'
                this.ttt=true
                this.$http.post(`product/product/findById/${row.tid}`).then(data => {
                    this.empInfo = data.data;
                    this.defaultPic = data.data.picPath;
                })
                this.dialogFormVisible=true
            },
            handleSelectionChange(val) {
                console.log(val)
                this.multipleSelection = [];
                for (let valKey in val) {
                    this.multipleSelection.push(val[valKey].tid)
                }
            },
            resetForm() {
                this.dialogFormVisible=false
                this.reload();
                this.defaultPic = "1.jpg";
            },
            listByRoute(){
                if(this.ltname.labelName == null){
                    this.$http.post("product/product/selectAll").then(data => {
                        this.list = data.data;
                    })
                    this.reload();
                }else {
                    this.$http.post("product/product/listByLname",this.ltname).then(data => {
                        this.list = data.data;
                    })
                }
            },
            updateState(row){
                this.$confirm('此操作将修改此商品状态, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'success'
                }).then(() => {
                    if (row.state == 0){
                        this.$http.post("product/product/saveOrUpdate", {state:1,tid:row.tid}).then(data => {
                            this.$message({
                                type: 'success',
                                message: '成功!'
                            });
                            this.reload();
                        })
                    }else if(row.state == 1){
                        this.$http.post("product/product/saveOrUpdate", {state:0,tid:row.tid}).then(data => {
                            this.$message({
                                type: 'success',
                                message: '成功!'
                            });
                            this.reload();
                        })
                    }else {
                        this.$message({
                            type: 'info',
                            message: '请求错误!'
                        });
                    }
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消修改'
                    });
                });
            },
            // 图片上传成功之后调用的方法
            handleAvatarSuccess (res, file) {
                console.log("上传的结果")
                console.log(res);
                console.log("上传的文件信息")
                console.log(file)
                if (res.code === 1) {
                    this.defaultPic = res.pic;
                    this.$message({
                        message: '上传成功',
                        type: 'success'
                    })
                } else {
                    this.notify('上传失败', 'error')
                }
            },
            // 图片上传之前调用的方法，验证上传的是否是图片
            beforeAvatarUpload (file) {
                const isJPG = file.type === 'image/jpeg'
                const isLt2M = file.size / 1024 / 1024 < 10
                if (!isJPG) {
                    this.$message.error('上传头像图片只能是 JPG 格式!')
                }
                if (!isLt2M) {
                    this.$message.error('上传头像图片不符合规范!')
                }
                return isJPG && isLt2M
            },
            // 上传图片
            insertUrl(){
                return `http://localhost:8092/product/product/insertProductPic`;
            },
            // 获取图片
            getUrl (picPath) {
                return `http://localhost:8092/product/product/findProductPicByPath?name=`+picPath;
            },
        }
    }
</script>

<style scoped>
    .productPicWidth{
        width: 100px;
        height: 100px;
    }
</style>
